package io.renren.modules.study.controller;


import io.renren.common.annotation.Login;
import io.renren.common.config.ListPageUtils;
import io.renren.common.config.SensitiveWordFilter;
import io.renren.common.utils.R;
import io.renren.modules.study.entity.*;
import io.renren.modules.study.service.CourseService;
import io.renren.modules.sys.dto.CollectDto;
import io.renren.modules.sys.dto.TeacherAndCourseMustKnow;
import io.renren.modules.sys.entity.UserEntity;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

//import io.renren.modules.sys.service.RedisService;
//import io.renren.modules.sys.service.RedisService;

@RestController
@RequestMapping("/api/course")
@Api(tags = "课程接口")
public class CourseController {

    @Autowired
    CourseService courseService;

    @Autowired
    UserService userService;

    @Autowired
    TokenService tokenService;
//    @Autowired
//    RedisService redisService;
//    @Autowired
//    @Autowired
//    RedisService redisService;


    @PostMapping("getCourseList")
    @ApiOperation("获得课程列表")
    public R getCourseList(@ApiIgnore @RequestBody Map<String, Object> params) {
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        List courseList = courseService.getCourseList(params);

        if (courseList.size() != 0) {
            ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if (list.size() > 0) {
                return R.ok("课程查询成功", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("课程查询成功", 100).put("data", list).put("nextNum", pageNum + 1);
        }
        return R.ok("课程空空如也", 100).put("data", courseList).put("nextNum", pageNum + 1);
    }


    @GetMapping("getsearchData")
    @ApiOperation("获得搜索条件")
    public R getsearchData() {

        Map map = courseService.getsearchData();
        return R.ok().put("data", map);
    }

    @GetMapping("pcGetCourseById")
    @ApiOperation("用Id获得课程详情")
    public R pcGetCourseById(@RequestParam(value = "courseId") Integer courseId) {
        Course courseDetail = courseService.getCourseById(courseId);
        return R.ok().put("data", courseDetail);
    }

    @Login
    @GetMapping("learn/{id}")
    @ApiOperation("获得课程")
    public R learn(@PathVariable("id") Integer id, @RequestAttribute("userId") Integer userId) {
        Course course = null;

        course = courseService.getCourseById(id, userId);
        return R.ok().put("data", course);
    }

    /**
     * 查看我的收藏   查询课程需要积分的数量 课程的名字title 课程的图片 introduce
     * 收藏本课程的人数
     * parameter  当前用户的userId
     * 解决流程：通过当前的userId 查询当前用户的收藏课程id列表 通过列表数据中的id
     * 获取收藏课程的具体信息
     */
    @PostMapping("getMyCollectionCouseList")
    @Login
    @ApiOperation("查看我的收藏")
    public R getMyCollectionCouseList(@RequestBody CollectDto collectDto) {
        int pageSize = collectDto.getPageSize();
        int pageNum = collectDto.getPageNum();
        List MyCollectionCourseList = courseService.getMyCollectionCouseList(collectDto);

        if (MyCollectionCourseList.size() != 0) {
            ListPageUtils pageUtil = new ListPageUtils(MyCollectionCourseList, pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if (list.size() > 0) {
                return R.ok("查看收藏课程成功", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("查看收藏课程成功", 100).put("data", list).put("nextNum", pageNum + 1);
        }
        return R.ok("您还未收藏课程！", 100).put("data", MyCollectionCourseList).put("nextNum", pageNum + 1);
    }

    /**
     * 查看当前收藏课程的具体信息
     */
    @PostMapping("getMyCollectionCouse")
    @Login
    @ApiOperation("查看我的收藏课程的具体信息")
    public R getMyCollectionCouse(@RequestBody CollectDto collectDto) {
        List MyCollectionCouse = courseService.getMyCollectionCouse(collectDto);
        return R.ok("查看当前课程成功", 100).put("data", MyCollectionCouse);
    }


    /**
     * 添加我的收藏的数量
     * 参数：当前课程的id和当前用户的id userId courseId
     */
    @PostMapping("addCourseCount")
    @Login
    @ApiOperation("增加当前课程的收藏数量")
    public R addCourseCount(@RequestBody CollectDto course) {
        int count = courseService.addCourseCount(course);
        if (count != 0) {
            courseService.addCollectionCourse(course);
            return R.ok("添加我的收藏成功", 100);
        }
        return R.error(101, "网络故障请重试");
    }


    /**
     * 减少当前课程的收藏数量
     * 参数：当前课程的id和当前用户的id userId courseId
     */
    @PostMapping("delCourseCount")
    @Login
    @ApiOperation("增加当前课程的收藏数量")
    public R delCourseCount(@RequestBody CollectDto course) {
        int count = courseService.delCourseCount(course);
        if (count != 0) {
            courseService.delCollectionCourse(course);
            return R.ok("取消我的收藏成功", 100);
        }
        return R.error(101, "网络故障请重试");
    }

    /**
     * 查询当前课程的讲师的信息和课程须知
     */
    @PostMapping("getTeacherAndCourseMustKnow")
    @ApiOperation("查询当前课程的讲师的信息和课程须知")
    public R getTeacherAndCourseMustKnow(@RequestBody Course course) {
        TeacherAndCourseMustKnow teacherAndCourseMustKnow = courseService.getTeacherAndCourseMustKnow(course);
        return R.ok("查询当前课程的讲师的信息和课程须知成功", 100).put("data", teacherAndCourseMustKnow);
    }

    /**
     * 判断当前课程是否被收藏
     * "0"为未收藏 "1"为已收藏
     */
    @PostMapping("checkIsCollection")
    @Login
    @ApiOperation("判断当前课程是否被收藏")
    public R checkIsCollection(@RequestBody CollectDto collectDto) {
        List list = courseService.checkIsCollection(collectDto);
        if (list.size() != 0) {
            return R.ok("success", 100).put("data", 1);
        }
        return R.ok("success", 100).put("data", 0);
    }

    /**
     * 根据title进行模糊查询
     */
    @PostMapping("getCourseByTitleLike")
    @ApiOperation("根据title进行模糊查询")
    public R getCourseByTitleLike(@RequestBody Map params) {
        String word = params.get("word").toString();
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        params.put("word", word);
        if (word == null || "".equals(word)) {
            return R.ok("查询条件不能为空", 101);
        }
        List courseList = courseService.getCourseByTitleLike(params);
        if (courseList.size() != 0) {
            ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if (list.size() > 0) {
                return R.ok("查询成功", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("查询成功", 100).put("data", list).put("nextNum", pageNum + 1);
        }
        return R.ok("没有符合条件的课程！", 100).put("data", courseList).put("nextNum", pageNum + 1);
    }

    /**
     * 过滤敏感字符
     *
     * @param str
     */
    public String wordFilter(@RequestBody String str) {
        SensitiveWordFilter sw = new SensitiveWordFilter();
        sw.InitializationWork();
        long startNumer = System.currentTimeMillis();
        System.out.println("被检测字符长度:" + str.length());
        str = sw.filterInfo(str);
        long endNumber = System.currentTimeMillis();
        System.out.println("耗时(毫秒):" + (endNumber - startNumer));
        System.out.println("过滤之后:" + str);
        return str;
    }


    /**
     * 给当前课程添加评论
     * 评论的id 课程的id
     */
    @Login
    @PostMapping("saveCourseComment")
    @ApiOperation("给当前课程添加评论")
    public R saveCourseComment(@RequestBody CourseComment courseComment) {
        String content = courseComment.getContent();
        if (content != null && !"".equals(content)) {
            String token = courseComment.getToken();
            Long userId = tokenService.getUserIdByToken(token);
            UserEntity user = userService.getUserByUserId(userId);
            //过滤敏感字
            courseComment.setContentB(wordFilter(courseComment.getContent()).getBytes());
            courseComment.setContent("");
            courseComment.setUserId(userId);
            courseComment.setUserHeadImage(user.getHeadImg());
            //courseComment.setUserName(new String(user.getNickNameB()));
            courseComment.setUserName("");
            courseComment.setUserNameB(user.getNickNameB());
            courseService.saveCourseComment(courseComment);
            System.out.println(courseComment.getContent());
            CourseComment c = courseService.getUserComment(courseComment);
            c.setUserName(new String(c.getUserNameB()));
            c.setContent(new String(c.getContentB()));
            return R.ok("课程添加评论成功", 100).put("courseComment", c);
        }
        return R.error(101, "评论不能为空");
    }


    /**
     * 删除评论
     */
    @Login
    @PostMapping("delCourseComment")
    @ApiOperation("删除课程的评论")
    public R delCourseComment(@RequestBody CourseComment courseComment) {
        String token = courseComment.getToken();
        Long userId = tokenService.getUserIdByToken(token);
        courseComment.setUserId(userId);
        courseService.delCourseComment(courseComment);
        return R.ok("删除评论成功", 100);
    }

    /**
     * 根据用户Id获取发表的评论
     */
    @Login
    @PostMapping("getCourseCommentByUserId")
    @ApiOperation("获取个人发表的评论")
    public R getCourseCommentByUserId(@RequestBody Map params) {
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        List courseCommentList = courseService.getCourseCommentByUserId(params);
        if (courseCommentList.size() > 0) {
            ListPageUtils pageUtil = new ListPageUtils(courseCommentList, pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    CourseComment c = (CourseComment) list.get(i);
                    if ("".equals(c.getUserName())) {
                        c.setUserName(new String(c.getUserNameB()));
                    }
                    if ("".equals(c.getContent())) {
                        c.setContent(new String(c.getContentB()));
                    }
                }
                return R.ok("查询个人评论成功", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("查询个人评论成功", 100).put("data", list).put("nextNum", pageNum + 1);
        }
        return R.ok("评论空空如也~", 100).put("data", courseCommentList).put("nextNum", pageNum + 1);
    }

    /**
     * 根据课程获取评论列表
     */
    @Login
    @PostMapping("getCourseComment")
    @ApiOperation("获取课程的评论")
    public R getCourseComment(@RequestBody Map params) {
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        List courseCommentList = courseService.getCourseComment(params);
        if (courseCommentList.size() > 0) {
            ListPageUtils pageUtil = new ListPageUtils(courseCommentList, pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    CourseComment c = (CourseComment) list.get(i);
                    if ("".equals(c.getUserName())) {
                        c.setUserName(new String(c.getUserNameB()));
                    }
                    if ("".equals(c.getContent())) {
                        c.setContent(new String(c.getContentB()));
                    }
                }
                return R.ok("查询课程评论成功", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("查询课程评论成功", 100).put("data", list).put("nextNum", pageNum + 1);
        }
        return R.ok("评论空空如也~", 100).put("data", courseCommentList).put("nextNum", pageNum + 1);
    }


    /**
     * 获取第一层分类
     */
    @GetMapping("getFirstClassification")
    public R getFirstClassification() {

        List list = courseService.getFirstClassification();
        return R.ok("", 100).put("data", list);
    }

    /**
     * 获取课程 根据classification_id
     */
    @PostMapping("getCourses")
    public R getCourses(@RequestBody Map map) {
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        List courseList = courseService.getCourses(map);
        if (courseList.size() > 0) {
            ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if (list.size() > 0) {
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
        }
        return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
    }

    /**
     * 获取分类列表
     */
    @GetMapping("getClassification")
    public R getClassification(@RequestParam(value = "parentId") Integer parentId) {
        List list = courseService.getClassification(parentId);
        for (int i = 0; i < list.size(); i++) {
            CourseClassification c = (CourseClassification) list.get(i);
            c.setList(findChild(c.getId()));
        }
        return R.ok("", 100).put("data", list);
    }


    private List findChild(Integer parentId) {
        // List<CourseClassification> l = new ArrayList<>();
        List list = courseService.getClassification(parentId);
        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                CourseClassification c = (CourseClassification) list.get(i);
                List ll = findChild(c.getId());
                // list.add(c);
                c.setList(ll);
            }
        }
        return list;
    }

    /**
     * 排序课程
     */
    @PostMapping("courseListByHot")
    public R courseListByTime(@RequestBody Map map) {
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        List<Course> courseList;
        if (map.get("classificationId") != null) {
            //请求最后一层
            if ("asc".equals(map.get("mode"))) {
                courseList = courseService.courseListByHot(map);
            } else {
                courseList = courseService.courseListByHotDesc(map);
            }
            //分页
            if (courseList.size() > 0) {
                ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if (list.size() > 0) {
                    return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
                }
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
        } /*else if (map.get("directionId") != null) {
            //请求第一层
            if ("asc".equals(map.get("mode"))) {
                courseList = courseService.getFirstCourseListByHot(map);
            } else {
                courseList = courseService.getFirstCourseListByHotDesc(map);
            }
            //分页
            if (courseList.size() > 0) {
                ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if (list.size() > 0) {
                    return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
                }
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
        }*/
        return R.error(101, "参数有误");
    }

    @PostMapping("courseListByTime")
    public R courseListByHot(@RequestBody Map map) {
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        List<Course> courseList;
        if (map.get("classificationId") != null) {
            if ("asc".equals(map.get("mode"))) {
                courseList = courseService.courseListByTime(map);
            } else {
                courseList = courseService.courseListByTimeDesc(map);
            }
            if (courseList.size() > 0) {
                ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if (list.size() > 0) {
                    return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
                }
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
        }
        /*if (map.get("directionId") != null) {
            if ("asc".equals(map.get("mode"))) {
                courseList = courseService.getFirstCourseListByTime(map);
            } else {
                courseList = courseService.getFirstCourseListByTimeDesc(map);
            }
            if (courseList.size() > 0) {
                ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if (list.size() > 0) {
                    return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
                }
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
        }*/
        return R.error(101, "参数有误");
    }

    @PostMapping("courseListByPrice")
    public R courseListByPrice(@RequestBody Map map) {
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        List<Course> courseList;
        if (map.get("classificationId") != null) {
            if ("asc".equals(map.get("mode"))) {
                courseList = courseService.courseListByPrice(map);
            } else {
                courseList = courseService.courseListByPriceDesc(map);
            }
            if (courseList.size() > 0) {
                ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if (list.size() > 0) {
                    return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
                }
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
        } /*else if (map.get("directionId") != null) {
            if ("asc".equals(map.get("mode"))) {
                courseList = courseService.getFirstcourseListByPrice(map);
            } else {
                courseList = courseService.getFirstcourseListByPriceDesc(map);
            }
            if (courseList.size() > 0) {
                ListPageUtils pageUtil = new ListPageUtils(courseList, pageSize);
                List list = pageUtil.getPagedList(pageNum);
                if (list.size() > 0) {
                    return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
                }
                return R.ok("", 100).put("data", list).put("nextNum", pageNum + 1);
            }
            return R.ok("", 100).put("data", courseList).put("nextNum", pageNum + 1);
        }*/
        return R.error(101, "参数有误");
    }

    /*@PostMapping("cList")
    public R cList(@RequestBody Map map){
    List<Course> list ;
        if("collection_count".equals(map.get("name")) && "asc".equals(map.get("mode"))){
            //按照收藏正序排序
            list = courseService.courseListByHot(map);
        }else{
            list = courseService.courseListByHotDesc(map);
        }
        //else if("collectionCount".equals(map.get("name")) && "desc".equals(map.get("mode"))){

       // }
        return R.ok("",100).put("list",list);
    }*/

    @GetMapping("getLearnBanner")
    @ApiOperation("获取学习轮播图数据")
    public R getLearnBannerData() {
        List list = courseService.getLearnBannerData();


        return R.ok("查询成功", 100).put("data", list);
    }


    /**
     * 随机获取八个课程
     */
    @GetMapping("courseRecommend")
    @ApiOperation("随机获六个课程")
    public R courseRecommend(){
        //获取课程的id列表
        List<Integer> idList = courseService.getCourseIdList();
        //int count = courseService.getCourseCount();
        if(idList.size() <=0){
            return null;
        }
        if(idList.size() <6 && idList.size()> 0){
            List courseList = courseService.getAllCourse();
            return R.ok("",100).put("data",courseList);
        }
        //随机数的list
        List<Integer> randomList = getRandom(idList.size(),6);
        List returnList = new ArrayList();
        for (int o = 0;o<randomList.size();o++){
            Course course = courseService.getCoursesNameAndOther(idList.get(randomList.get(o)));
            returnList.add(course);
        }

return R.ok("",100).put("data",returnList);

    }

    /**
     * 获取随机数
     * @param bound 范围 count 数量
     * @return
     */
    public List getRandom(int bound,int count){
        // 生成 [0-n) 个不重复的随机数
        // list 用来保存这些随机数
        Set set = new HashSet();
        Random rand = new Random();
        int c =0;
        while(c+set.size() != c+count){
            int i = rand.nextInt(bound-1)+1;
            set.add(i);
            c++;
        }
        List list = new ArrayList(set);
        return list;
    }


    /**
     * 每个分类中获取两门课程
     */
    @GetMapping("getTwoCourseInDrication")
    public R getTwoCourseInDrication(){
        List list = new ArrayList();

        //获取分类的id列表
        List<Direction> dricationList = courseService.getDricationList();
        for(Direction direction : dricationList){

            DricationTwo dricationTwo = new DricationTwo();
            //存放子课程的list
            List list2 = new ArrayList();
            int directionId = direction.getId();
            dricationTwo.setDricationId(Long.valueOf(directionId));
            dricationTwo.setDricationName(direction.getName());
            //获取同分类下的课程id列表
            List<Integer> oneDriectionCourseIdList = courseService.getCourseIdByDirectionId(direction.getId());
            if(oneDriectionCourseIdList.size()<=0){
                //这个分类下没有上线课程
                dricationTwo.setCourseList(null);
                list.add(dricationTwo);
            }else if(oneDriectionCourseIdList.size()<=2 && oneDriectionCourseIdList.size()> 0){
                //这个分类下就两个课程或更少
                for(int i = 0;i<oneDriectionCourseIdList.size();i++){
                    Course course = courseService.getCoursesNameAndOther(oneDriectionCourseIdList.get(i));
                    list2.add(course);
                }
                dricationTwo.setCourseList(list2);
                list.add(dricationTwo);
            }else{
                //获取随机数
                List<Integer> randomIdList = getRandom(oneDriectionCourseIdList.size(),2);
                for(int i=0;i<randomIdList.size();i++){
                    //获取这个分类中的这个课程的id
                    int oneDriectionCourseId = oneDriectionCourseIdList.get(randomIdList.get(i));
                    Course course = courseService.getCoursesNameAndOther(oneDriectionCourseId);
                    //将随机选到的课程放到list中
                    list2.add(course);
                }
                dricationTwo.setCourseList(list2);
                list.add(dricationTwo);
            }
        }
        return R.ok("",100).put("data",list);
    }


}
